<template>
  <div class="legal-chat-container">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="header-content">
        <el-icon class="header-icon"><Document /></el-icon>
        <h1>法智小帮手 - 智能法律咨询</h1>
        <span class="header-subtitle">专业法律问题解答助手</span>
      </div>
    </div>

    <div class="chat-layout">
      <!-- 侧边栏 -->
      <div class="sidebar" width="280px">
        <div class="sidebar-header">
          <el-avatar :size="60" :icon="Document" class="sidebar-avatar" />
          <div class="sidebar-info">
            <h3>法智小帮手</h3>
            <span class="status online">在线</span>
          </div>
        </div>

        <div class="sidebar-features">
          <div class="feature-item">
            <el-icon><ChatDotRound /></el-icon>
            <span>智能法律咨询</span>
          </div>
          <div class="feature-item">
            <el-icon><Clock /></el-icon>
            <span>7×24小时服务</span>
          </div>
          <div class="feature-item">
            <el-icon><Lock /></el-icon>
            <span>对话隐私保护</span>
          </div>
        </div>

        <el-button 
          class="new-chat-btn" 
          type="primary" 
          @click="newChat" 
          :icon="Plus"
        >
          开始新会话
        </el-button>
      </div>

      <!-- 主聊天区域 -->
      <div class="main-chat">
        <div class="chat-window">
          <!-- 消息列表 -->
          <div class="message-list" ref="messageListRef">
            <!-- 欢迎消息 -->
            <div v-if="messages.length === 0" class="welcome-message">
              <div class="welcome-content">
                <el-icon class="welcome-icon"><ChatDotRound /></el-icon>
                <h3>欢迎使用法智小帮手！</h3>
                <p>我是您的智能法律顾问，可以为您提供：</p>
                <ul>
                  <li>法律问题咨询解答</li>
                  <li>法律条文查询解读</li>
                  <li>法律风险评估</li>
                  <li>维权建议指导</li>
                </ul>
                <p>请在下方的输入框中描述您遇到的法律问题...</p>
              </div>
            </div>

            <!-- 聊天消息 -->
            <div
              v-for="(message, index) in messages"
              :key="index"
              :class="[
                'message',
                message.isUser ? 'user-message' : 'bot-message'
              ]"
            >
              <div class="message-content">
                <div class="message-avatar">
                  <el-avatar
                    v-if="message.isUser"
                    :size="40"
                    :icon="User"
                    class="user-avatar"
                  />
                  <el-avatar
                    v-else
                    :size="40"
                    :icon="ChatDotRound"
                    class="bot-avatar"
                  />
                </div>
                
                <div class="message-bubble">
                  <div class="message-text" v-html="message.content"></div>
                  
                  <!-- 加载动画 -->
                  <div 
                    v-if="message.isTyping" 
                    class="typing-indicator"
                  >
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <span class="dot"></span>
                  </div>
                </div>
              </div>
              
              <div class="message-time">
                {{ formatTime(message.timestamp) }}
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <div class="input-container">
              <el-input
                v-model="inputMessage"
                placeholder="请输入您遇到的法律问题，例如：劳动合同纠纷、财产继承、交通事故赔偿等..."
                @keyup.enter="sendMessage"
                type="textarea"
                :rows="3"
                resize="none"
                :disabled="isSending"
                class="message-input"
              >
                <template #append>
                  <el-button 
                    @click="sendMessage" 
                    :disabled="!inputMessage.trim() || isSending" 
                    type="primary"
                    class="send-btn"
                    :icon="Promotion"
                  >
                    发送
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <div class="quick-questions">
              <span class="quick-title">快速提问：</span>
              <el-tag
                v-for="(question, idx) in quickQuestions"
                :key="idx"
                class="quick-tag"
                @click="inputMessage = question"
              >
                {{ question }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <!-- <div v-if="isSending" class="loading-overlay">
      <div class="loading-content">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>法智小帮手正在思考中...</p>
      </div>
    </div> -->
  </div>
</template>

<script setup>
import { onMounted, ref, watch, nextTick } from 'vue'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'
import { 
  Document, User, ChatDotRound, Plus, Promotion, 
  Clock, Lock, Loading 
} from '@element-plus/icons-vue'

const messageListRef = ref()
const isSending = ref(false)
const uuid = ref()
const inputMessage = ref('')
const messages = ref([])

// 快速提问示例
const quickQuestions = ref([
  '劳动合同纠纷怎么处理？',
  '离婚财产如何分割？',
  '交通事故赔偿标准是什么？',
  '房屋租赁合同注意事项',
  '知识产权保护措施'
])

onMounted(() => {
  initUUID()
  watch(messages, () => scrollToBottom(), { deep: true })
})

const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const sendMessage = () => {
  if (inputMessage.value.trim() && !isSending.value) {
    sendRequest(inputMessage.value.trim())
    inputMessage.value = ''
  }
}

const sendRequest = async (message) => {
  isSending.value = true
  
  // 添加用户消息
  const userMsg = {
    isUser: true,
    content: message,
    isTyping: false,
    timestamp: new Date()
  }
  messages.value.push(userMsg)

  // 添加机器人加载消息
  const botMsg = {
    isUser: false,
    content: '',
    isTyping: true,
    timestamp: new Date()
  }
  messages.value.push(botMsg)
  
  scrollToBottom()

  const lastMsg = messages.value[messages.value.length - 1]
  
  try {
    const response = await axios.post(
      '/allow/chat',
      { memoryId: uuid.value, message },
      {
        responseType: 'text',
        onDownloadProgress: (progressEvent) => {
          if (progressEvent.event && progressEvent.event.target) {
            const fullText = progressEvent.event.target.responseText
            if (fullText) {
              let newText = fullText.substring(lastMsg.content.length)
              lastMsg.content += convertStreamOutput(newText)
              scrollToBottom()
            }
          }
        }
      }
    )
    
    // 流结束后更新状态
    lastMsg.isTyping = false
    lastMsg.timestamp = new Date()
    
  } catch (error) {
    console.error('请求错误:', error)
    lastMsg.content = '抱歉，请求失败。请检查网络连接或稍后重试。'
    lastMsg.isTyping = false
    lastMsg.timestamp = new Date()
  } finally {
    isSending.value = false
  }
}

// 初始化 UUID
const initUUID = () => {
  let storedUUID = localStorage.getItem('legal_chat_uuid')
  if (!storedUUID) {
    storedUUID = uuidv4()
    localStorage.setItem('legal_chat_uuid', storedUUID)
  }
  uuid.value = uuidToNumber(storedUUID)
}

const uuidToNumber = (uuid) => {
  let number = 0
  for (let i = 0; i < uuid.length && i < 6; i++) {
    const hexValue = uuid[i]
    number = number * 16 + (parseInt(hexValue, 16) || 0)
  }
  return number % 1000000
}

// 转换特殊字符
const convertStreamOutput = (output) => {
  return output
    .replace(/\n/g, '<br>')
    .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
}

const newChat = () => {
  if (confirm('确定要开始新的会话吗？当前对话记录将被清空。')) {
    messages.value = []
    localStorage.removeItem('legal_chat_uuid')
    initUUID()
  }
}
</script>

<style scoped>
.legal-chat-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 20px 40px;
  color: white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-icon {
  font-size: 32px;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-subtitle {
  opacity: 0.8;
  font-size: 14px;
}

.chat-layout {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
  height: calc(100vh - 120px);
}

.sidebar {
  width: 280px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  text-align: center;
  margin-bottom: 30px;
}

.sidebar-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin-bottom: 15px;
}

.sidebar-info h3 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-weight: 600;
}

.status.online {
  color: #52c41a;
  font-size: 12px;
}

.sidebar-features {
  flex: 1;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  margin: 8px 0;
  border-radius: 8px;
  transition: all 0.3s ease;
  color: #5a6270;
}

.feature-item:hover {
  background: #f0f4ff;
  color: #667eea;
}

.feature-item .el-icon {
  font-size: 18px;
}

.new-chat-btn {
  margin-top: auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  height: 48px;
  font-weight: 500;
}

.main-chat {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.chat-window {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #fafafa;
}

.welcome-message {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.welcome-icon {
  font-size: 48px;
  color: #667eea;
  margin-bottom: 20px;
}

.welcome-content h3 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.welcome-content ul {
  text-align: left;
  max-width: 400px;
  margin: 15px auto;
}

.message {
  margin-bottom: 24px;
}

.message-content {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.bot-avatar {
  background: #52c41a;
}

.message-bubble {
  max-width: 70%;
  background: white;
  padding: 16px 20px;
  border-radius: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.message-text {
  line-height: 1.6;
  word-wrap: break-word;
}

.message-text :deep(br) {
  content: '';
  display: block;
  margin: 8px 0;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  margin-top: 8px;
}

.dot {
  width: 6px;
  height: 6px;
  background-color: currentColor;
  border-radius: 50%;
  animation: pulse 1.4s infinite ease-in-out both;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

.message-time {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 8px;
}

.user-message .message-time {
  text-align: right;
}

.bot-message .message-time {
  text-align: left;
}

.input-area {
  border-top: 1px solid #e8e8e8;
  background: white;
  padding: 20px;
}

.input-container {
  margin-bottom: 16px;
}

.message-input :deep(.el-textarea__inner) {
  border: none;
  border-radius: 12px;
  background: #f5f7fa;
  padding: 16px;
  font-size: 14px;
}

.send-btn {
  height: 100%;
  border-radius: 0 12px 12px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.quick-questions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-title {
  font-size: 12px;
  color: #666;
}

.quick-tag {
  cursor: pointer;
  border: none;
  background: #f0f4ff;
  color: #667eea;
  transition: all 0.3s ease;
}

.quick-tag:hover {
  background: #667eea;
  color: white;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.loading-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.loading-icon {
  font-size: 32px;
  color: #667eea;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-layout {
    flex-direction: column;
    padding: 10px;
    height: calc(100vh - 80px);
  }
  
  .sidebar {
    width: 100%;
    order: 2;
    margin-top: 10px;
  }
  
  .main-chat {
    order: 1;
  }
  
  .header {
    padding: 15px 20px;
  }
  
  .header-content h1 {
    font-size: 20px;
  }
  
  .message-bubble {
    max-width: 85%;
  }
  
  .quick-questions {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .quick-title {
    margin-bottom: 8px;
  }
}

@media (max-width: 480px) {
  .header-content {
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
  
  .message-bubble {
    max-width: 90%;
    padding: 12px 16px;
  }
  
  .input-area {
    padding: 15px;
  }
  .message-input :deep(.el-textarea__inner) {
    padding: 12px;
  }
}
</style>
